package com.koron.ticket.line.work.common.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.common.core.business.workflow.bean.properties.WorkflowProperties;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.StringUtils;
import com.koron.ticket.line.work.common.bean.FifteenTables;
import com.koron.ticket.line.work.common.bean.FourteenTables;
import com.koron.ticket.line.work.common.bean.Print;
import com.koron.ticket.line.work.common.bean.SecurityArrangementBean;
import com.koron.ticket.line.work.enums.TicketStatus;
import com.koron.ticket.line.work.enums.TicketType;
import com.koron.ticket.line.work.workticket.bean.WorkTicket;
import com.koron.ticket.line.work.workticket.bean.WorkTicketQuery;
import com.koron.ticket.line.work.workticket.service.WorkTicketService;
import com.koron.ticket.line.workChange.ticketchange.bean.TicketChange;
import com.koron.ticket.line.workChange.ticketchange.enums.TicketChangeType;
import com.koron.ticket.line.workChange.ticketchange.service.TicketChangeService;
import com.koron.ticket.work.securityarrangement.bean.SecurityArrangement;
import com.koron.ticket.work.securityarrangement.bean.SecurityArrangementQuery;
import com.koron.ticket.work.securityarrangement.service.SecurityArrangementService;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workPermit.bean.WorkPermitQuery;
import com.koron.ticket.work.workPermit.service.WorkPermitService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workend.bean.WorkEndQuery;
import com.koron.ticket.work.workend.service.WorkEndService;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.bean.WorkFlowQuery;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workinfo.bean.WorkInfo;
import com.koron.ticket.work.workinfo.bean.WorkInfoQuery;
import com.koron.ticket.work.workinfo.service.WorkInfoService;
import com.koron.ticket.work.worklocation.bean.WorkLocationBean;
import com.koron.ticket.work.worklocation.service.WorkLocationService;
import com.koron.ticket.work.workmember.bean.WorkMember;
import com.koron.ticket.work.workmember.bean.WorkMemberQuery;
import com.koron.ticket.work.workmember.service.WorkMemberService;
import com.koron.ticket.work.workteam.bean.WorkTeam;
import com.koron.ticket.work.workteam.bean.WorkTeamQuery;
import com.koron.ticket.work.workteam.service.WorkTeamService;
import com.koron.ticket.workchange.ticketchangecontent.bean.TicketChangeContent;
import com.koron.ticket.workchange.ticketchangedelay.bean.TicketChangeDelay;
import com.koron.ticket.workchange.ticketchangedirector.bean.TicketChangeDirector;
import com.koron.ticket.workchange.ticketchangeinterrupt.bean.TicketChangeInterrupt;
import com.koron.ticket.workchange.ticketchangemember.bean.TicketChangeMember;
import com.koron.ticket.workchange.ticketchangesecurityarrangement.bean.TicketChangeSecurityArrangement;
import org.apache.commons.lang3.SerializationUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.bean.BeanUtil.copyProperties;

@Service("lineFifteenTablesService")
public class FifteenTablesService {

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    private static Date currentTime = new Date();

    @Autowired
    private SecurityArrangementService securityArrangementService;

    @Autowired
    private WorkTicketService lineWorkTicketService;

    @Autowired
    private WorkInfoService workInfoService;

    @Autowired
    private WorkTeamService workTeamService;

    @Autowired
    private WorkMemberService workMemberService;

    @Autowired
    private WorkLocationService worklocationservice;

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkPermitService workPermitService;

    @Autowired
    private WorkEndService workEndService;

    @Autowired
    private TicketChangeService ticketChangeService;

    @Autowired
    private FourteenTablesService lineFourteenTablesService;

    @Autowired
    private FeignForConfigure feignForConfigure;

    /**
     * 填写-保存数据
     * 1. workTicketId为空是新增
     * 2. workTicketId不为空是更新
     *
     * @param factory
     * @param fifteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    public String writeSave(SessionFactory factory, FifteenTables fifteenTables) {
        WorkTicket workTicket = fifteenTables.getWorkTicket();
        String workTicketId = workTicket.getId();

        // 1. 如果id为空，说明是新增
        if (StringUtils.isEmpty(workTicketId)) {
            // 1.1 先设置工作票的填写状态
            workTicket.setStatus(1);
            // 1.2 将预览标志设置为预览
            workTicket.setPreviewFlag(0);
            workTicketId = this.insert(factory, fifteenTables);
        } // 2. 如果id不为空，说明数据已存在，对现有的数据进行更新
        else {
            this.update(factory, fifteenTables);
        }
        return workTicketId;
    }

    /**
     * 新增五张表的数据
     * 1. 工作票主票-w_ticket_work
     * 2. 工作票详情-w_ticket_work_info
     * 3. 工作班组-w_ticket_work_team（可以多个）
     * 4. 工作班组成员-w_ticket_work_member（可以多个）
     * 5. 安全措施项-w_ticket_work_security_arrangement（可以多个）
     *
     * @param factory
     * @param fifteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    @Transactional(rollbackFor = Exception.class)
    public String insert(SessionFactory factory, FifteenTables fifteenTables) {
        // 1. 新增workTicket，workInfo，workTeam，workMember的数据
        FourteenTables fourteenTables = new FourteenTables();
        fourteenTables.setWorkTicket(fifteenTables.getWorkTicket());
        fourteenTables.setWorkInfo(fifteenTables.getWorkInfo());
        fourteenTables.setWorkTeamList(fifteenTables.getWorkTeamList());
        fourteenTables.setWorkMemberList(fifteenTables.getWorkMemberList());
        fourteenTables.setWorkLocationList(fifteenTables.getWorkLocationList());
        String workTicketId = lineFourteenTablesService.insert(factory, fourteenTables);

        // 2. 新增securityArrangement的数据
        List<SecurityArrangement> securityArrangementList = fifteenTables.getSecurityArrangementList();
        if (StringUtils.isNotEmpty(securityArrangementList)) {
            securityArrangementList.stream().forEach(s -> {
                s.setWorkTicketId(workTicketId);
                s.setId(CodeTools.getCode32());
                s.setDeleteFlag(0);
                s.setCreateTime(currentTime);
            });
            securityArrangementService.batchInsert(factory, securityArrangementList);
//            for (SecurityArrangement securityArrangement : securityArrangementList) {
//                securityArrangement.setWorkTicketId(workTicketId);
//                securityArrangement.setId(CodeTools.getCode32());
//                securityArrangement.setDeleteFlag(0);
//                securityArrangement.setCreateTime(currentTime);
//                securityArrangementService.insert(factory, securityArrangement);
//            }
        }
        // TODO: 6. 新增操作记录

        return workTicketId;
    }

    /**
     * 更新五张表的数据
     * 1. 工作票主票-w_ticket_work
     * 2. 工作票详情-w_ticket_work_info
     * 3. 工作班组-w_ticket_work_team（可以多个）
     * 4. 工作班组成员-w_ticket_work_member（可以多个）
     * 5. 安全措施项-w_ticket_work_security_arrangement（可以多个）
     *
     * @param factory
     * @param fifteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SessionFactory factory, FifteenTables fifteenTables) {
        // 1. 更新workTicket，workInfo，workTeam，workMember的数据
        FourteenTables fourteenTables = new FourteenTables();
        fourteenTables.setWorkTicket(fifteenTables.getWorkTicket());
        fourteenTables.setWorkInfo(fifteenTables.getWorkInfo());
        fourteenTables.setWorkTeamList(fifteenTables.getWorkTeamList());
        fourteenTables.setWorkMemberList(fifteenTables.getWorkMemberList());
        fourteenTables.setWorkLocationList(fifteenTables.getWorkLocationList());
        lineFourteenTablesService.update(factory, fourteenTables);

        // 2. 更新securityArrangement的数据
        String workTicketId = fifteenTables.getWorkTicket().getId();
        List<SecurityArrangement> securityArrangementList = fifteenTables.getSecurityArrangementList();
        // 2.1 删除原有的数据
        securityArrangementService.deleteByWorkTicketId(factory, workTicketId);
        // 2.2 再新增现在的安全措施项
        if (StringUtils.isNotEmpty(securityArrangementList)) {
            securityArrangementList.stream().forEach(s -> {
                s.setWorkTicketId(workTicketId);
                s.setId(CodeTools.getCode32());
                s.setDeleteFlag(0);
                s.setCreateTime(currentTime);
            });
            securityArrangementService.batchInsert(factory, securityArrangementList);
//            for (SecurityArrangement securityArrangement : securityArrangementList) {
//                securityArrangement.setId(CodeTools.getCode32());
//                securityArrangement.setWorkTicketId(workTicketId);
//                securityArrangement.setDeleteFlag(0);
//                securityArrangement.setCreateTime(currentTime);
//                securityArrangementService.insert(factory, securityArrangement);
//            }
        }
        // TODO: 6. 操作记录

    }

    public FifteenTables addByType(String type) {
        FifteenTables fifteenTables = new FifteenTables();

        // 1. 设置工作票类型
        WorkTicket workTicket = new WorkTicket();
        workTicket.setType(type);
        fifteenTables.setWorkTicket(workTicket);
        // 2. 设置安全措施项
        List<SecurityArrangement> securityArrangementList = new ArrayList<>();
        // 2.1 从eam-service-configure模块中获取原始数据
        Response response = feignForConfigure.queryList(type);
        // 2.2 将拿出来的数据赋值给对象
        JSONArray array = JSONArray.parseArray(JSONArray.toJSONString(response.getData()));
        for (int i = 0; i < array.size(); i++) {
            SecurityArrangement securityArrangement = new SecurityArrangement();
            JSONObject jsonObject = array.getJSONObject(i);
            securityArrangement.setItem((String) jsonObject.get("item"));
            securityArrangement.setRequiredFlag((Integer) jsonObject.get("requiredFlag"));
            securityArrangement.setSort((Integer) jsonObject.get("sort"));
            securityArrangementList.add(securityArrangement);

        }
        fifteenTables.setSecurityArrangementList(securityArrangementList);
        // 3. 设置当前用户信息
        fifteenTables.setCreateByName(getCurrUser().getName());
        fifteenTables.setCreateTime(new Date());

        return fifteenTables;
    }

    public FifteenTables getById(SessionFactory factory, String id) {
        FifteenTables fifteenTables = new FifteenTables();

        // 1. 根据id查询工作票主票
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
        fifteenTables.setWorkTicket(workTicket);
        // 2. 根据workTicketId查询工作票详情
        WorkInfoQuery workInfoQuery = new WorkInfoQuery();
        workInfoQuery.setWorkTicketId(id);
        WorkInfo workInfo = workInfoService.getSingle(factory, workInfoQuery);
        fifteenTables.setWorkInfo(workInfo);
        // 3. 根据workTicketId查询工作班组
        WorkTeamQuery workTeamQuery = new WorkTeamQuery();
        workTeamQuery.setWorkTicketId(id);
        List<WorkTeam> workTeamList = workTeamService.getList(factory, workTeamQuery);
        fifteenTables.setWorkTeamList(workTeamList);
        // 4. 根据workTicketId查询工作班组成员
        WorkMemberQuery workMemberQuery = new WorkMemberQuery();
        workMemberQuery.setWorkTicketId(id);
        List<WorkMember> workMemberList = workMemberService.getList(factory, workMemberQuery);
        fifteenTables.setWorkMemberList(workMemberList);
        // 工作地点
        List<WorkLocationBean> worklocationlist = worklocationservice.getList(factory, id);
        fifteenTables.setWorkLocationList(worklocationlist);
        // 5. 根据workTicketId查询安全项措施
        SecurityArrangementQuery securityArrangementQuery = new SecurityArrangementQuery();
        securityArrangementQuery.setWorkTicketId(id);
        List<SecurityArrangement> securityArrangementList = securityArrangementService.getList(factory, securityArrangementQuery);
        fifteenTables.setSecurityArrangementList(securityArrangementList);
        // 6. 根据status查看签名、待许可、工作待终结、工作票待终结的相关数据
        Integer status = workTicket.getStatus();
        if (status >= TicketStatus.WRITE.getStatus()) {
            // 6.1 只要不是填写状态（除了电力线路第一种工作票），都有签名
            WorkFlowQuery workFlowQuery = new WorkFlowQuery();
            workFlowQuery.setWorkTicketId(id);
            List<WorkFlow> workFlowList = workFlowService.getList(factory, workFlowQuery);
            fifteenTables.setWorkFlowList(workFlowList);
        }
        if (status >= TicketStatus.PERMIT.getStatus()) {
            // 6.2 状态是待许可,及以上的时候，查出待许可的信息
            WorkPermitQuery workPermitQuery = new WorkPermitQuery();
            workPermitQuery.setWorkTicketId(id);
            WorkPermit workPermit = workPermitService.getSingle(factory, workPermitQuery);
            fifteenTables.setWorkPermit(workPermit);
        }
        if (status >= TicketStatus.WORK_END.getStatus()) {
            // 6.3 状态是工作待终结,及以上的时候，查出工作终结的信息,以及工作票变更的相关信息
            WorkEndQuery workEndQuery = new WorkEndQuery();
            workEndQuery.setWorkTicketId(id);
            List<WorkEnd> workEndList = workEndService.getList(factory, workEndQuery);
            fifteenTables.setWorkEndList(workEndList);

            TicketChange ticketChange = ticketChangeService.getByWorkTicketId(factory, id);
            fifteenTables.setTicketChange(ticketChange);
        }

        fifteenTables.setCreateBy(fifteenTables.getWorkTicket().getCreateUserId());
        fifteenTables.setDeptId(fifteenTables.getWorkTicket().getCreateDept());
        return fifteenTables;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(SessionFactory factory, String id) {
        // 当id不为空的时候，才有数据删除
        if (!StringUtils.isEmpty(id)) {
            // 1. 删除十四张表中的数据
            lineFourteenTablesService.deleteById(factory, id);
            // 2. 删除安全措施相关数据
//            securityArrangementService.deleteByWorkTicketId(factory, id);

//            // 1. 先删除主票信息
//            lineWorkTicketService.deleteById(factory, id);
//            // 2. 再删除工作票详情
//            workInfoService.deleteByWorkTicketId(factory, id);
//            // 3. 再删除工作班组数据
//            workTeamService.deleteByWorkTicketId(factory, id);
//            // 4. 再删除工作班组成员数据
//            workMemberService.deleteByWorkTicketId(factory, id);
//            // 5. 再删除安全措施项
//            securityArrangementService.deleteByWorkTicketId(factory, id);
//            // TODO 6. 查看工作流是否要删除
//            String workflow = workFlowHandler.queryView(id);
//            if (!StringUtils.isEmpty(workflow)) {
//                // 6.1 如果有数据，则需要删除
//                workFlowHandler.end(id);
//            }
        }
    }

    /**
     * 填写-提交数据
     * 1. 保存当前数据
     * 2. 工作流初始化
     * 3. 记录操作人
     *
     * @param factory
     * @param fifteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    public String writeSubmitByWorkFlowType(SessionFactory factory, FifteenTables fifteenTables, String workFlowType) {
        WorkTicket workTicket = fifteenTables.getWorkTicket();
        String workTicketId = workTicket.getId();
        String code = workTicket.getCode();
        String account = getCurrUser().getAccount();
        String name = getCurrUser().getName();
        String phone = getCurrUser().getPhone();
        Date currentTime = new Date();
        Map<String, String> form = new HashMap<>();
        form.put("user", account);

        // 1. 保存当前的数据
        // 1.1 因为是提交，所以装态要变成待签发
        workTicket.setStatus(TicketStatus.SIGN.getStatus());
        if (StringUtils.isEmpty(workTicketId)) {
            // 1.2 id为空，数据是新增的，workTicketId在新增的时候获取
            workTicketId = this.insert(factory, fifteenTables);
        } else {
            this.update(factory, fifteenTables);
        }
        // 2. 进入工作流
        WorkflowProperties wfp = WorkflowProperties.init(workFlowType);
        workFlowHandler.start(wfp, workTicketId, code,workTicket.getTitle(), form);
        // 3. 记录操作人
        WorkFlow workFlow = new WorkFlow();
        workFlow.setWorkTicketId(workTicketId);
        workFlow.setType("填写人");
        workFlow.setAccount(account);
        workFlow.setName(name);
        workFlow.setPhone(phone);
        workFlow.setOperationTime(currentTime);
        workFlow.setDeleteFlag(0);
        workFlowService.insert(factory, workFlow, TicketStatus.WRITE.getStatus());

        return workTicketId;
    }

    /**
     * 打印预览：打印最多十五张表的数据
     * 电气第一/二种工作票，机械工作票使用该方法进行打印预览
     * 1. 工作票主票-w_ticket_work
     * 2. 工作票详情-w_ticket_work_info
     * 3. 工作班组-w_ticket_work_team
     * 4. 工作班组成员-w_ticket_work_member
     * 5. 签名-w_ticket_work_flow
     * 6. 待许可信息-w_ticket_work_permit
     * 7. 终结信息-w_ticket_work_end
     * 8. 安全措施项-w_ticket_work_security_arrangement
     * 9-15: 工作变更项- TicketChange:包含w_ticket_change_director/content/delay/director/interrupt/member/securityarrangement 的数据
     *
     * @param factory
     * @param id
     * @param ticketType
     * @return
     */
    public List<Print> getPrintData(SessionFactory factory, String id, String ticketType) {
        List<Print> result = new ArrayList<>();
        Print print = new Print();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
        Integer status = workTicket.getStatus();

        WorkTeamQuery workTeamQuery = new WorkTeamQuery();
        workTeamQuery.setWorkTicketId(id);
        List<WorkTeam> workTeamList = workTeamService.getList(factory, workTeamQuery);
        String workTeamListString = "";
        if (workTeamList.size() > 0) {
            workTeamListString = workTeamList.stream().map(WorkTeam::getWorkTeamName).collect(Collectors.joining(","));
        }

        WorkMemberQuery workMemberQuery = new WorkMemberQuery();
        workMemberQuery.setWorkTicketId(id);
        List<WorkMember> workMemberList = workMemberService.getList(factory, workMemberQuery);
        String workMemberListString = "";
        if (workMemberList.size() > 0) {
            workMemberListString = workMemberList.stream().map(WorkMember::getMemberName).collect(Collectors.joining(","));
        }

        WorkFlowQuery workFlowQuery = new WorkFlowQuery();
        workFlowQuery.setWorkTicketId(id);
        List<WorkFlow> workFlowList = workFlowService.getList(factory, workFlowQuery);

        WorkPermitQuery workPermitQuery = new WorkPermitQuery();
        workPermitQuery.setWorkTicketId(id);
        WorkPermit workPermit = workPermitService.getSingle(factory, workPermitQuery);

        WorkEndQuery workEndQuery = new WorkEndQuery();
        workEndQuery.setWorkTicketId(id);
        List<WorkEnd> workEndList = workEndService.getList(factory, workEndQuery);

        // 2. 工作票票号
        print.setCode(workTicket.getCode());
        // 3. 工作负责人名称
        print.setDirectorName(workTicket.getDirectorName());
        // 4. 工作班组名称
        print.setWorkTeamNameListString(workTeamListString);
        // 5. 工作班成员名称
        print.setMemberNameListString(workMemberListString);
        // 6. 工作班成员数量（工作负责人+班组成员）
        print.setNumber(workTicket.getNumber());
        // 7. 工作内容
        print.setContent(workTicket.getContent());
        // 8. 工作地点
        List<WorkLocationBean> worklocationlist = worklocationservice.getList(factory, id);
        String worklocationlistStr = "";
        if (worklocationlist.size() > 0) {
            worklocationlistStr = worklocationlist.stream().map(WorkLocationBean::getLocationName).collect(Collectors.joining(","));
        }
        print.setLocationName(worklocationlistStr);
//        print.setLocationName(workTicket.getLocationName());
        // 9. 计划开始时间
        if (workTicket.getEstimatedStartTime() != null) {
            // 兼容计划开始时间为空的情况
            print.setEstimatedStartTime(DateUtil.format(workTicket.getEstimatedStartTime(), "yyyy年MM月dd日 HH时mm分"));
        }
        // 10. 计划结束时间
        if (workTicket.getEstimatedEndTime() != null) {
            // 兼容计划结束时间为空的情况
            print.setEstimatedEndTime(DateUtil.format(workTicket.getEstimatedEndTime(), "yyyy年MM月dd日 HH时mm分"));
        }
        // 11. 工作要求的安全措施

        // 11.2 电气第一/二种工作票
        SecurityArrangementBean securityarrangement = new SecurityArrangementBean();
        securityArrangementForPrint(factory, id, securityarrangement);
        copyProperties(securityarrangement, print, false);

        if (status >= TicketStatus.SIGN.getStatus()) {
            // 12. 签发人, 签发时间
            if (workFlowList.size() > 0) {
                for (WorkFlow workFlow : workFlowList) {
                    if (workFlow.getStatus().equals(TicketStatus.SIGN.getStatus()) && workFlow.getDeleteFlag().equals(0)) {
                        //签发人
                        print.setSignName(workFlow.getName());
                        //签发时间
                        Opt<String> optdate = Opt.ofNullable(DateUtil.format(workFlow.getOperationTime(), "yyyy年MM月dd日 HH时mm分"));
                        print.setSignTime(optdate.orElse(""));
                        break;
                    }
                }
            }
        }

        // 13. 会签人：电气第一/二种工作票
        if (status >= TicketStatus.COUNTERSIGN.getStatus()) {
            for (WorkFlow workFlow : workFlowList) {
                // 20211116: 兼容电子签的时候deleteFlag=1/2,不显示的情况
                if (workFlow.getStatus().equals(TicketStatus.COUNTERSIGN.getStatus()) && workFlow.getDeleteFlag().equals(0)) {
                    print.setCountersignName(workFlow.getName());
                    break;
                }
            }
        }

        if (status >= TicketStatus.PERMIT.getStatus()) {
            // 14. 满足工作要求的安全措施
//            Integer securityStatus = workPermit.getSecurityStatus();
            Opt<WorkPermit> workPermitOpt = Opt.ofNullable(workPermit);
            Integer securityStatus = workPermitOpt.map(WorkPermit::getSecurityStatus).orElse(null);
            if (securityStatus != null) {
                // 兼容待许可无数据
                if (securityStatus == 1) {
                    print.setSecurityStatus("是");
                } else if (securityStatus == 0) {
                    print.setSecurityStatus("否");
                }
            } else {
                print.setSecurityStatus("");
            }
            // 15. 需补充或调整的安全措施
            print.setSecurityArrangementChange(workPermitOpt.map(WorkPermit::getSecurityArrangementChange).orElse(null));
            // 16. 带电的母线，导线
            print.setWorkLocationDevice(workPermitOpt.map(WorkPermit::getWorkLocationDevice).orElse(null));
            // 17. 带电的隔离开关
            print.setWorkLocationSwitch(workPermitOpt.map(WorkPermit::getWorkLocationSwitch).orElse(null));
            // 18. 其他
            print.setAttention(workPermitOpt.map(WorkPermit::getAttention).orElse(null));
            // 19. 其他安全注意事项
            print.setOtherNotes(workPermitOpt.map(WorkPermit::getOtherNotes).orElse(null));
            // 20. 现场满足工作要求时间
//            print.setWorkTime(Opt.ofNullable(DateUtil.format(workPermit.getWorkTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
            print.setWorkTime(DateUtil.format(workPermitOpt.map(WorkPermit::getWorkTime).orElse(null), "yyyy年MM月dd日 HH时mm分"));
            // 21. 工作待许可-工作许可人/工作负责人/工作跟踪责任人
            for (WorkFlow workFlow : workFlowList) {
                if (workFlow.getStatus().equals(TicketStatus.PERMIT.getStatus()) && workFlow.getDeleteFlag().equals(0)) {
                    String type = workFlow.getType();
                    // 20211213：type由"工作许可人"变更为"name0"
                    if (type.equals("name0")) {
                        print.setPermitName(workFlow.getName());
                    } // 20211213：type由"工作负责人"变更为"name1"
                    else if (type.equals("name1")) {
                        print.setDirectorNameForPermit(workFlow.getName());
                    } // 20211213：type由"工作跟踪负责人"变更为"name2"
                    else if (type.equals("name2")) {
                        print.setPermitTrackName(workFlow.getName());
                    }
                }
            }
        }

        // 22. 工作待终结状态/工作票待终结：先更新工作待终结，再更新工作票待终结，最后更新工作票变更数据（打印控件数据要求）
        if (status >= TicketStatus.WORK_END.getStatus()) {
            // 22.1 工作待终结
            for (WorkEnd workEnd : workEndList) {
                if (workEnd.getStatus() == TicketStatus.WORK_END.getStatus()) {
                    // 22.1.1 工作待终结时间
//                    Opt<String> optdate = Opt.ofNullable(DateUtil.format(workEnd.getEndTime(), "yyyy年MM月dd日 HH时mm分"));
//                    print.setEndTimeForWorkEnd(optdate.orElse(""));
                    print.setEndTimeForWorkEnd(DateUtil.format(workEnd.getEndTime(), "yyyy年MM月dd日 HH时mm分"));
                    // 22.1.2 工作终结-工作负责人/工作许可人
                    for (WorkFlow workFlow : workFlowList) {
                        if (workFlow.getStatus().equals(TicketStatus.WORK_END.getStatus()) && workFlow.getDeleteFlag().equals(0)) {
                            String type = workFlow.getType();
                            // 20211213：type由"工作负责人"变更为"name0"
                            if (type.equals("name0")) {
                                print.setDirectorNameForWorkEnd(workFlow.getName());
//                                print.setEndTimeForWorkEnd(DateUtil.format(workFlow.getOperationTime(), "yyyy年MM月dd日 HH时mm分"));
                            } // 20211213：type由"工作许可人"变更为"name1"
                            else if (type.equals("name1")) {
                                print.setPermitNameForWorkEnd(workFlow.getName());
                            }
                        }
                    }
                }
            }
            // 22.2 工作票待终结
            if (status >= TicketStatus.TICKET_END.getStatus()) {
                for (WorkEnd workEnd : workEndList) {
                    if (workEnd.getStatus().equals(TicketStatus.TICKET_END.getStatus())) {
                        // 22.2.1 工作票待终结时间
//                        Opt<String> optdate = Opt.ofNullable(DateUtil.format(workEnd.getEndTime(), "yyyy年MM月dd日 HH时mm分"));
//                        print.setEndTimeForTicketEnd(optdate.orElse(""));
                        // 22.2.2 三条信息
                        String endInformation = workEnd.getEndInformation();
                        // 20211213: 兼容数据为空的情况
                        if (StringUtils.isNotEmpty(endInformation)) {
                            List<String> three = StrUtil.split(endInformation,";");
                            print.setTicketEndFirstNumber(three.get(0));
                            print.setTicketEndSecondNumber(three.get(1));
                            print.setTicketEndThirdNumber(three.get(2));
                        }
                        // 22.2.3 值班负责人
                        for (WorkFlow workFlow : workFlowList) {
                            if (workFlow.getStatus().equals(TicketStatus.TICKET_END.getStatus()) && workFlow.getDeleteFlag().equals(0)) {
                                print.setDutyPersonNameForTicketEnd(workFlow.getName());
                                break;
                            }
                        }
                        // 22.2.4 备注
                        print.setDescription(workEnd.getEndDescription());
                    }
                    // 工作票结束后才显示 完成时间
                    if (status >= TicketStatus.ARCHIVED.getStatus()) {
                        Opt<String> optdate = Opt.ofNullable(DateUtil.format(workEnd.getEndTime(), "yyyy年MM月dd日 HH时mm分"));
                        print.setEndTimeForTicketEnd(optdate.orElse(""));
                    }
                }
            }
            // 22.3 工作票变更信息
            TicketChange ticketChange = ticketChangeService.getByWorkTicketId(factory, id);
            List<TicketChangeDirector> ticketChangeDirectorList = ticketChange.getTicketChangeDirectorList();
            List<TicketChangeDelay> ticketChangeDelayList = ticketChange.getTicketChangeDelayList();
            List<TicketChangeInterrupt> ticketChangeInterruptList = ticketChange.getTicketChangeInterruptList();
            List<TicketChangeContent> ticketChangeContentList = ticketChange.getTicketChangeContentList();
            List<TicketChangeMember> ticketChangeMemberList = ticketChange.getTicketChangeMemberList();
            List<TicketChangeSecurityArrangement> ticketChangeSecurityArrangementList = ticketChange.getTicketChangeSecurityArrangementList();

            // 22.3.1 工作负责人变更
            if (ticketChangeDirectorList.size() > 0) {
                for (TicketChangeDirector director : ticketChangeDirectorList) {
                    Print newPrint = SerializationUtils.clone(print);
//                    Print newPrint = new Print();
//                    copyProperties(print, newPrint);
//                    BeanUtil.copyProperties();
                    newPrint.setChangeColumnIdentifier(TicketChangeType.DIRECTOR_CHANGE.getType());
                    newPrint.setChangeColumn1(Opt.ofNullable(director.getFormerDirectorName()).orElse(""));
                    newPrint.setChangeColumn2(Opt.ofNullable(director.getNewDirectorName()).orElse(""));
                    newPrint.setChangeColumn3(Opt.ofNullable(director.getPermitName()).orElse(""));
//                    String changeTime = simpleDateFormat.format(director.getChangeTime());
                    newPrint.setChangeColumn4(Opt.ofNullable(DateUtil.format(director.getChangeTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
                    newPrint.setChangeColumn5(Opt.ofNullable(director.getSingName()).orElse(""));
                    newPrint.setChangeColumn5(Optional.of(director.getSingName()).orElse(""));
                    result.add(newPrint);
                }
            } else {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                BeanUtil.copyProperties(print, newPrint);
                newPrint.setChangeColumnIdentifier(TicketChangeType.DIRECTOR_CHANGE.getType());
                result.add(newPrint);
            }
            // 22.3.2 工作票延期
            if (ticketChangeDelayList.size() > 0) {
                for (TicketChangeDelay delay : ticketChangeDelayList) {
//                    Print newPirnt = SerializationUtils.clone(print);
                    Print newPrint = new Print();
                    copyProperties(print, newPrint);
                    newPrint.setChangeColumnIdentifier(TicketChangeType.TICKET_DELAY.getType());
//                    String delayTime = simpleDateFormat.format(delay.getDelayTime());
                    newPrint.setChangeColumn1(Opt.ofNullable(DateUtil.format(delay.getDelayTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
                    newPrint.setChangeColumn2(Opt.ofNullable(delay.getDirectorName()).orElse(""));
                    newPrint.setChangeColumn3(Opt.ofNullable(delay.getDutyPersonName()).orElse(""));
                    result.add(newPrint);
                }
            } else {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                copyProperties(print, newPrint);
                newPrint.setChangeColumnIdentifier(TicketChangeType.TICKET_DELAY.getType());
                result.add(newPrint);
            }
            // 22.3.3 工作间断
            if (ticketChangeInterruptList.size() > 0) {
                for (TicketChangeInterrupt interrupt : ticketChangeInterruptList) {
                    Print newPrint = SerializationUtils.clone(print);
//                    Print newPrint = new Print();
//                    copyProperties(print, newPrint);
                    newPrint.setChangeColumnIdentifier(TicketChangeType.WORK_INTERRUPT.getType());
//                    String interruptTime = simpleDateFormat.format(interrupt.getInterruptTime());
                    newPrint.setChangeColumn1(Opt.ofNullable(DateUtil.format(interrupt.getInterruptTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
                    newPrint.setChangeColumn2(Opt.ofNullable(interrupt.getDirectorNameInterrupt()).orElse(""));
                    newPrint.setChangeColumn3(Opt.ofNullable(interrupt.getPermitNameInterrupt()).orElse(""));
//                    String startTime = simpleDateFormat.format(interrupt.getStartTime());
                    newPrint.setChangeColumn4(Opt.ofNullable(DateUtil.format(interrupt.getStartTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
                    newPrint.setChangeColumn5(Opt.ofNullable(interrupt.getPermitNameStart()).orElse(""));
                    newPrint.setChangeColumn6(Opt.ofNullable(interrupt.getDirectorNameStart()).orElse(""));
                    result.add(newPrint);
                }
            } else {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                 copyProperties(print, newPrint);
                newPrint.setChangeColumnIdentifier(TicketChangeType.WORK_INTERRUPT.getType());
                result.add(newPrint);
            }
            // 22.3.4 增加工作内容
            if (ticketChangeContentList.size() > 0) {
                for (TicketChangeContent content : ticketChangeContentList) {
                    Print newPrint = SerializationUtils.clone(print);
//                    Print newPrint = new Print();
//                     copyProperties(print, newPrint);
                    newPrint.setChangeColumnIdentifier(TicketChangeType.ADD_WORK_CONTENT.getType());
                    newPrint.setChangeColumn1(Opt.ofNullable(content.getContent()).orElse(""));
                    newPrint.setChangeColumn2(Opt.ofNullable(content.getDirectorName()).orElse(""));
                    newPrint.setChangeColumn3(Opt.ofNullable(content.getPermitName()).orElse(""));
                    result.add(newPrint);
                }
            } else {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                 copyProperties(print, newPrint);
                newPrint.setChangeColumnIdentifier(TicketChangeType.ADD_WORK_CONTENT.getType());
                result.add(newPrint);
            }
            // 22.3.5 工作班成员变动
            if (ticketChangeMemberList.size() > 0) {
                for (TicketChangeMember member : ticketChangeMemberList) {
                    Print newPrint = SerializationUtils.clone(print);
//                    Print newPrint = new Print();
//                     copyProperties(print, newPrint);
                    newPrint.setChangeColumnIdentifier(TicketChangeType.MEMBER_CHANGE.getType());
                    newPrint.setChangeColumn1(Opt.ofNullable(member.getDirectorName()).orElse(""));
                    newPrint.setChangeColumn2(Opt.ofNullable(member.getPermitName()).orElse(""));
//                    String changeTime = simpleDateFormat.format(member.getChangeTime());
                    newPrint.setChangeColumn3(Opt.ofNullable(DateUtil.format(member.getChangeTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
                    newPrint.setChangeColumn4(Opt.ofNullable(member.getAddMemberName()).orElse(""));
                    newPrint.setChangeColumn5(Opt.ofNullable(member.getDecreaseMemberName()).orElse(""));
                    result.add(newPrint);
                }
            } else {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                 copyProperties(print, newPrint);
                newPrint.setChangeColumnIdentifier(TicketChangeType.MEMBER_CHANGE.getType());
                result.add(newPrint);
            }
            // 22.3.6 部分安全措施变动
            if (ticketChangeSecurityArrangementList.size() > 0) {
                for (TicketChangeSecurityArrangement securityArrangement : ticketChangeSecurityArrangementList) {
                    Print newPrint = SerializationUtils.clone(print);
//                    Print newPrint = new Print();
//                     copyProperties(print, newPrint);
                    newPrint.setChangeColumnIdentifier(TicketChangeType.SECURITY_ARRANGEMENT_CHANGE.getType());
                    newPrint.setChangeColumn1(Opt.ofNullable(securityArrangement.getDirectorName()).orElse(""));
                    newPrint.setChangeColumn2(Opt.ofNullable(securityArrangement.getPermitName()).orElse(""));
//                    String changeTime = simpleDateFormat.format(securityArrangement.getChangeTime());
                    newPrint.setChangeColumn3(Opt.ofNullable(DateUtil.format(securityArrangement.getChangeTime(), "yyyy年MM月dd日 HH时mm分")).orElse(""));
                    newPrint.setChangeColumn4(Opt.ofNullable(securityArrangement.getSecurityArrangement()).orElse(""));
                    result.add(newPrint);
                }
            } else {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                 copyProperties(print, newPrint);
                newPrint.setChangeColumnIdentifier(TicketChangeType.SECURITY_ARRANGEMENT_CHANGE.getType());
                result.add(newPrint);
            }
        }
        // 23. 如果是在工作待终结状态之前，只有一条数据;
        if (status < TicketStatus.WORK_END.getStatus()) {
            // 23.1 在工作待终结状态之前，没有变更的数据，但是打印预览的时候需要展示，所以需要初始化这部分数据
            for (int i = 1; i < 7; i++) {
                Print newPrint = SerializationUtils.clone(print);
//                Print newPrint = new Print();
//                BeanUtil.copyProperties(print, newPrint);
                if (i == 1) {
                    newPrint.setChangeColumnIdentifier(TicketChangeType.DIRECTOR_CHANGE.getType());
                } else if (i == 2) {
                    newPrint.setChangeColumnIdentifier(TicketChangeType.TICKET_DELAY.getType());
                } else if (i == 3) {
                    newPrint.setChangeColumnIdentifier(TicketChangeType.WORK_INTERRUPT.getType());
                } else if (i == 4) {
                    newPrint.setChangeColumnIdentifier(TicketChangeType.ADD_WORK_CONTENT.getType());
                } else if (i == 5) {
                    newPrint.setChangeColumnIdentifier(TicketChangeType.MEMBER_CHANGE.getType());
                } else if (i == 6) {
                    newPrint.setChangeColumnIdentifier(TicketChangeType.SECURITY_ARRANGEMENT_CHANGE.getType());
                }
                result.add(newPrint);
            }
        }

        return result;
    }

    /**
     * 电气第一/二种工作票添加安全措施到打印对象种
     *
     * @param factory
     * @param id
     * @param securityarrangement
     */
    public void securityArrangementForPrint(SessionFactory factory, String id, SecurityArrangementBean securityarrangement) {
        SecurityArrangementQuery securityArrangementQuery = new SecurityArrangementQuery();
        securityArrangementQuery.setWorkTicketId(id);
        List<SecurityArrangement> securityArrangementList = securityArrangementService.getList(factory, securityArrangementQuery);
        if (securityArrangementList != null && securityArrangementList.size() > 0) {
            for (SecurityArrangement securityArrangement : securityArrangementList) {
                Integer sort = securityArrangement.getSort();
                String item = securityArrangement.getItem();
                String value = securityArrangement.getValue();
                //这个如果 描述null 打印不会显示安全措施。 要显示空的安全措施，描述请填空格
                if (StringUtils.isEmpty(value)) {
                    continue;
                }
                if (sort == 1) {
                    securityarrangement.setSecurityArrangementSort1(sort);
                    securityarrangement.setSecurityArrangementItem1(item);
                    securityarrangement.setSecurityArrangementValue1(value);
                } else if (sort == 2) {
                    securityarrangement.setSecurityArrangementSort2(sort);
                    securityarrangement.setSecurityArrangementItem2(item);
                    securityarrangement.setSecurityArrangementValue2(value);
                } else if (sort == 3) {
                    securityarrangement.setSecurityArrangementSort3(sort);
                    securityarrangement.setSecurityArrangementItem3(item);
                    securityarrangement.setSecurityArrangementValue3(value);
                } else if (sort == 4) {
                    securityarrangement.setSecurityArrangementSort4(sort);
                    securityarrangement.setSecurityArrangementItem4(item);
                    securityarrangement.setSecurityArrangementValue4(value);
                } else if (sort == 5) {
                    securityarrangement.setSecurityArrangementSort5(sort);
                    securityarrangement.setSecurityArrangementItem5(item);
                    securityarrangement.setSecurityArrangementValue5(value);
                } else if (sort == 6) {
                    securityarrangement.setSecurityArrangementSort6(sort);
                    securityarrangement.setSecurityArrangementItem6(item);
                    securityarrangement.setSecurityArrangementValue6(value);
                } else if (sort == 7) {
                    securityarrangement.setSecurityArrangementSort7(sort);
                    securityarrangement.setSecurityArrangementItem7(item);
                    securityarrangement.setSecurityArrangementValue7(value);
                } else if (sort == 8) {
                    securityarrangement.setSecurityArrangementSort8(sort);
                    securityarrangement.setSecurityArrangementItem8(item);
                    securityarrangement.setSecurityArrangementValue8(value);
                } else if (sort == 9) {
                    securityarrangement.setSecurityArrangementSort9(sort);
                    securityarrangement.setSecurityArrangementItem9(item);
                    securityarrangement.setSecurityArrangementValue9(value);
                } else if (sort == 10) {
                    securityarrangement.setSecurityArrangementSort10(sort);
                    securityarrangement.setSecurityArrangementItem10(item);
                    securityarrangement.setSecurityArrangementValue10(value);
                } else if (sort == 11) {
                    securityarrangement.setSecurityArrangementSort11(sort);
                    securityarrangement.setSecurityArrangementItem11(item);
                    securityarrangement.setSecurityArrangementValue11(value);
                } else if (sort == 12) {
                    securityarrangement.setSecurityArrangementSort12(sort);
                    securityarrangement.setSecurityArrangementItem12(item);
                    securityarrangement.setSecurityArrangementValue12(value);
                } else if (sort == 13) {
                    securityarrangement.setSecurityArrangementSort13(sort);
                    securityarrangement.setSecurityArrangementItem13(item);
                    securityarrangement.setSecurityArrangementValue13(value);
                } else if (sort == 14) {
                    securityarrangement.setSecurityArrangementSort14(sort);
                    securityarrangement.setSecurityArrangementItem14(item);
                    securityarrangement.setSecurityArrangementValue14(value);
                } else if (sort == 15) {
                    securityarrangement.setSecurityArrangementSort15(sort);
                    securityarrangement.setSecurityArrangementItem15(item);
                    securityarrangement.setSecurityArrangementValue15(value);
                } else if (sort == 16) {
                    securityarrangement.setSecurityArrangementSort16(sort);
                    securityarrangement.setSecurityArrangementItem16(item);
                    securityarrangement.setSecurityArrangementValue16(value);
                } else if (sort == 17) {
                    securityarrangement.setSecurityArrangementSort17(sort);
                    securityarrangement.setSecurityArrangementItem17(item);
                    securityarrangement.setSecurityArrangementValue17(value);
                } else if (sort == 18) {
                    securityarrangement.setSecurityArrangementSort18(sort);
                    securityarrangement.setSecurityArrangementItem18(item);
                    securityarrangement.setSecurityArrangementValue18(value);
                } else if (sort == 19) {
                    securityarrangement.setSecurityArrangementSort19(sort);
                    securityarrangement.setSecurityArrangementItem19(item);
                    securityarrangement.setSecurityArrangementValue19(value);
                } else if (sort == 20) {
                    securityarrangement.setSecurityArrangementSort20(sort);
                    securityarrangement.setSecurityArrangementItem20(item);
                    securityarrangement.setSecurityArrangementValue20(value);
                } else if (sort == 21) {
                    securityarrangement.setSecurityArrangementSort21(sort);
                    securityarrangement.setSecurityArrangementItem21(item);
                    securityarrangement.setSecurityArrangementValue21(value);
                } else if (sort == 22) {
                    securityarrangement.setSecurityArrangementSort22(sort);
                    securityarrangement.setSecurityArrangementItem22(item);
                    securityarrangement.setSecurityArrangementValue22(value);
                } else if (sort == 23) {
                    securityarrangement.setSecurityArrangementSort23(sort);
                    securityarrangement.setSecurityArrangementItem23(item);
                    securityarrangement.setSecurityArrangementValue23(value);
                } else if (sort == 24) {
                    securityarrangement.setSecurityArrangementSort24(sort);
                    securityarrangement.setSecurityArrangementItem24(item);
                    securityarrangement.setSecurityArrangementValue24(value);
                }
            }
        }
    }

//    public void securityArrangementForPrint(SessionFactory factory, String id, Print print) {
//        SecurityArrangementQuery securityArrangementQuery = new SecurityArrangementQuery();
//        securityArrangementQuery.setWorkTicketId(id);
//        List<SecurityArrangement> securityArrangementList = securityArrangementService.getList(factory, securityArrangementQuery);
//        if (securityArrangementList != null && securityArrangementList.size() > 0) {
//            for (SecurityArrangement securityArrangement : securityArrangementList) {
//                Integer sort = securityArrangement.getSort();
//                String item = securityArrangement.getItem();
//                String value = securityArrangement.getValue();
//                //这个如果 描述null 打印不会显示安全措施。 要显示空的安全措施，描述请填空格
//                if (StringUtils.isEmpty(value)) {
//                    continue;
//                }
//                if (sort == 1) {
//                    print.setSecurityArrangementSort1(sort);
//                    print.setSecurityArrangementItem1(item);
//                    print.setSecurityArrangementValue1(value);
//                } else if (sort == 2) {
//                    print.setSecurityArrangementSort2(sort);
//                    print.setSecurityArrangementItem2(item);
//                    print.setSecurityArrangementValue2(value);
//                } else if (sort == 3) {
//                    print.setSecurityArrangementSort3(sort);
//                    print.setSecurityArrangementItem3(item);
//                    print.setSecurityArrangementValue3(value);
//                } else if (sort == 4) {
//                    print.setSecurityArrangementSort4(sort);
//                    print.setSecurityArrangementItem4(item);
//                    print.setSecurityArrangementValue4(value);
//                } else if (sort == 5) {
//                    print.setSecurityArrangementSort5(sort);
//                    print.setSecurityArrangementItem5(item);
//                    print.setSecurityArrangementValue5(value);
//                } else if (sort == 6) {
//                    print.setSecurityArrangementSort6(sort);
//                    print.setSecurityArrangementItem6(item);
//                    print.setSecurityArrangementValue6(value);
//                } else if (sort == 7) {
//                    print.setSecurityArrangementSort7(sort);
//                    print.setSecurityArrangementItem7(item);
//                    print.setSecurityArrangementValue7(value);
//                } else if (sort == 8) {
//                    print.setSecurityArrangementSort8(sort);
//                    print.setSecurityArrangementItem8(item);
//                    print.setSecurityArrangementValue8(value);
//                } else if (sort == 9) {
//                    print.setSecurityArrangementSort9(sort);
//                    print.setSecurityArrangementItem9(item);
//                    print.setSecurityArrangementValue9(value);
//                } else if (sort == 10) {
//                    print.setSecurityArrangementSort10(sort);
//                    print.setSecurityArrangementItem10(item);
//                    print.setSecurityArrangementValue10(value);
//                } else if (sort == 11) {
//                    print.setSecurityArrangementSort11(sort);
//                    print.setSecurityArrangementItem11(item);
//                    print.setSecurityArrangementValue11(value);
//                } else if (sort == 12) {
//                    print.setSecurityArrangementSort12(sort);
//                    print.setSecurityArrangementItem12(item);
//                    print.setSecurityArrangementValue12(value);
//                } else if (sort == 13) {
//                    print.setSecurityArrangementSort13(sort);
//                    print.setSecurityArrangementItem13(item);
//                    print.setSecurityArrangementValue13(value);
//                } else if (sort == 14) {
//                    print.setSecurityArrangementSort14(sort);
//                    print.setSecurityArrangementItem14(item);
//                    print.setSecurityArrangementValue14(value);
//                } else if (sort == 15) {
//                    print.setSecurityArrangementSort15(sort);
//                    print.setSecurityArrangementItem15(item);
//                    print.setSecurityArrangementValue15(value);
//                } else if (sort == 16) {
//                    print.setSecurityArrangementSort16(sort);
//                    print.setSecurityArrangementItem16(item);
//                    print.setSecurityArrangementValue16(value);
//                } else if (sort == 17) {
//                    print.setSecurityArrangementSort17(sort);
//                    print.setSecurityArrangementItem17(item);
//                    print.setSecurityArrangementValue17(value);
//                } else if (sort == 18) {
//                    print.setSecurityArrangementSort18(sort);
//                    print.setSecurityArrangementItem18(item);
//                    print.setSecurityArrangementValue18(value);
//                } else if (sort == 19) {
//                    print.setSecurityArrangementSort19(sort);
//                    print.setSecurityArrangementItem19(item);
//                    print.setSecurityArrangementValue19(value);
//                } else if (sort == 20) {
//                    print.setSecurityArrangementSort20(sort);
//                    print.setSecurityArrangementItem20(item);
//                    print.setSecurityArrangementValue20(value);
//                } else if (sort == 21) {
//                    print.setSecurityArrangementSort21(sort);
//                    print.setSecurityArrangementItem21(item);
//                    print.setSecurityArrangementValue21(value);
//                } else if (sort == 22) {
//                    print.setSecurityArrangementSort22(sort);
//                    print.setSecurityArrangementItem22(item);
//                    print.setSecurityArrangementValue22(value);
//                } else if (sort == 23) {
//                    print.setSecurityArrangementSort23(sort);
//                    print.setSecurityArrangementItem23(item);
//                    print.setSecurityArrangementValue23(value);
//                } else if (sort == 24) {
//                    print.setSecurityArrangementSort24(sort);
//                    print.setSecurityArrangementItem24(item);
//                    print.setSecurityArrangementValue24(value);
//                }
//            }
//        }
//    }

    /**
     * 工作待终结/工作票待终结-保存：
     * 1. 保存workEnd数据
     * 2. 保存签名数据
     *
     * @param factory
     * @param workEnd
     * @param status
     */
    public void endSaveWithStatus(SessionFactory factory, WorkEnd workEnd, Integer status) {
        List<WorkFlow> workFlowList = workEnd.getWorkFlowList();
        lineWorkTicketService.checkTimeOut(factory, workEnd.getWorkTicketId(), workEnd.getUpdateTime());//检查信息是否过期
        // 1. 保存工作待终结阶段的数据
        workEndService.saveWithStatus(factory, workEnd, status);
        // 2. 保存签名的数据
        if (workFlowList != null && workFlowList.size() > 0) {
            for (WorkFlow workFlow : workFlowList) {
                workFlowService.save(factory, workFlow);
//                String workFlowId = workFlow.getId();
//                if (StringUtils.isEmpty(workFlowId)) {
//                    workFlowService.insert(factory, workFlow, status);
//                } else {
//                    workFlowService.update(factory, workFlow);
//                }
            }
        }
//        // 3. 将工作票预览标志设置为未预览
//        updatePreviewFlagById(factory, workTicketId);
    }

    public void updatePreviewFlagById(SessionFactory factory, String id) {
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
        workTicket.setPreviewFlag(1);
        lineWorkTicketService.update(factory, workTicket);
    }

    public void signOrCountersignOrAcceptSave(SessionFactory factory, WorkFlow workFlow) {
        String workTicketId = workFlow.getWorkTicketId();

        // 1. 保存签名数据
        workFlowService.save(factory, workFlow);
//        // 2. 将工作票预览标志设置为未预览
//        this.updatePreviewFlagById(factory, workTicketId);
    }

    /**
     * 待许可-保存
     * 1. 保存workPermit的数据
     * 2. 保存workFlow数据
     *
     * @param factory
     * @param workPermit
     */
    public void permitSave(SessionFactory factory, WorkPermit workPermit) {
        List<WorkFlow> workFlowList = workPermit.getWorkFlowList();
        String workTicketId = workPermit.getWorkTicketId();
        lineWorkTicketService.checkTimeOut(factory, workPermit.getWorkTicketId(), workPermit.getUpdateTime());//检查信息是否过期
        // 1. 保存待许可的数据
        workPermitService.save(factory, workPermit);
        // 2. 保存签名的数据
        if (workFlowList != null && workFlowList.size() > 0) {
            for (WorkFlow workFlow : workFlowList) {
                workFlowService.save(factory, workFlow);
            }
        }
        // 3. 将工作票预览标志设置为未预览
        this.updatePreviewFlagById(factory, workTicketId);
    }

//    /**
//     * 工作流回调接口：
//     * 1. 被驳回：仅将当前状态到被驳回状态的签名数据全部清除，其他数据保留
//     * 2. 通过：
//     * 2.1 签发阶段：签名数据保存；部分工作票需要生成工作票号，并跳到待接收阶段
//     * 2.2 会签阶段：签名数据保存；部分工作票需要生成工作票号
//     * 2.3 接收阶段：签名数据保存；将预览标志设为未预览；电力线路第二种工作票跳到工作待终结阶段
//     * 2.4 许可阶段：签名数据保存；许可数据保存；
//     * 2.5 工作待终结阶段：签名数据保存；终结数据保存；一级/二级动火工作票，跳到已归档阶段
//     *
//     * @param factory
//     * @param redirectQuery
//     * @return
//     * @throws ParseException
//     */
//    public String workflowUpdate(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
//        Integer operation = redirectQuery.getOperation();
//        String workTicketId = redirectQuery.getDataId();
//        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
//        workTicketQuery.setId(workTicketId);
//        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
//        Integer status = workTicket.getStatus();
//        String type = workTicket.getType();
//
//        // 1. 如果被驳回，返回对应状态，仅删除签名的数据，其他的数据不做处理
//        if (operation == 1) {
//            String rejectNodeCode = redirectQuery.getRejectNodeCode();
//            // 1.1 如果被驳回到填写状态
//            if (rejectNodeCode.contains("0")) {
//                Integer rejectStatus = TicketStatus.WRITE.getStatus();
//                this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                // 1.1 如果是（签发/会签/待接收）状态驳回到填写状态
////                if (status <= TicketStatus.ACCEPT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                } // 1.2 如果是待许可状态驳回到填写状态
////                if (status == TicketStatus.PERMIT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
////
////                } // 1.3 如果是（工作待终结/工作票待终结）驳回到填写状态
////                else if (status >= TicketStatus.WORK_END.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
//////                    workEndService.deleteByWorkTicketId(factory, workTicketId);
////                }
//                // 1.4 根据实际返回的驳回状态，进行更新
//                workTicket.setStatus(rejectStatus);
//            } else if (rejectNodeCode.contains("1")) {
//                Integer rejectStatus = TicketStatus.SIGN.getStatus();
//                this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                // 2.1 如果是（会签/待接收）状态驳回到签发状态
////                if (status <= TicketStatus.ACCEPT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                } // 2.2 如果是待许可驳回到签发状态
////                else if (status == TicketStatus.PERMIT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
////                } // 2.3 如果是(工作待终结/工作票待终结）驳回驳回到签发状态
////                else if (status >= TicketStatus.WORK_END.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
//////                    workEndService.deleteByWorkTicketId(factory, workTicketId);
////                }
//                // 2.4 根据实际返回的驳回状态，进行更新
//                workTicket.setStatus(rejectStatus);
//            } else if (rejectNodeCode.contains("2")) {
//                Integer rejectStatus = TicketStatus.COUNTERSIGN.getStatus();
//                this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                // 3.1 如果是待接收状态驳回到会签状态
////                if (status <= TicketStatus.ACCEPT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                } // 3.2 如果是待许可驳回到签发状态
////                else if (status == TicketStatus.PERMIT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
////                } // 3.3 如果是(工作待终结/工作票待终结）驳回驳回到签发状态
////                else if (status >= TicketStatus.WORK_END.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
//////                    workEndService.deleteByWorkTicketId(factory, workTicketId);
////                }
//                // 3.4 根据实际返回的驳回状态，进行更新
//                workTicket.setStatus(rejectStatus);
//            } else if (rejectNodeCode.contains("3")) {
//                Integer rejectStatus = TicketStatus.ACCEPT.getStatus();
//                this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                // 4.1 如果是待许可状态驳回到待接收状态
////                if (status == TicketStatus.PERMIT.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
////                } // 4.2 如果是(工作待终结/工作票待终结）驳回驳回到待接收状态
////                else if (status >= TicketStatus.WORK_END.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
//////                    workEndService.deleteByWorkTicketId(factory, workTicketId);
////                }
//                // 4.4 根据实际返回的驳回状态，进行更新
//                workTicket.setStatus(rejectStatus);
//            } else if (rejectNodeCode.contains("4")) {
//                Integer rejectStatus = TicketStatus.PERMIT.getStatus();
//                this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//                // 20211111: 如何是待许可状态，讲预览标志设置成未预览
//                workTicket.setPreviewFlag(1);
////                // 5.1 如果是(工作待终结/工作票待终结）驳回驳回到待许可
////                if (status >= TicketStatus.WORK_END.getStatus()) {
////                    this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
//////                    workPermitService.deleteByWorkTicketId(factory, workTicketId);
//////                    workEndService.deleteByWorkTicketId(factory, workTicketId);
////                }
////                // 5.3 根据实际返回的驳回状态，进行更新
//                workTicket.setStatus(rejectStatus);
//            } else if (rejectNodeCode.contains("5")) {
//                Integer rejectStatus = TicketStatus.WORK_END.getStatus();
//                // 6.1 只可能是工作票待终结状态驳回到工作待终结状态
//                this.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
////                workEndService.deleteByWorkTicketId(factory, workTicketId);
//                workTicket.setStatus(rejectStatus);
//            }
//            lineWorkTicketService.update(factory, workTicket);
//        } // 7. 如果通过，工作票进入下一个状态，并根据状态的不同进行不同的操作
//        else if (operation == 32) {
//            String formVariables = redirectQuery.getFormVariables();
//            Map<String, String> infoMap = TextUtil.toMapFromString(formVariables);
//            // 7.1 如果是签发状态，保存签名信息
//            if (status.equals(TicketStatus.SIGN.getStatus())) {
//                // 20211112: 电力线路第一种工作票在签发阶段能够保存多条数据
//                if (type.equals(TicketType.PowerLineFirst.getType())) {
//                    workFlowService.insertByStringMap(factory, formVariables, status);
//                } else {
//                    workFlowService.insertByMap(factory, infoMap, status);
//                }
//                // 20211111: 如果是机械工作票/电力线路第一种工作票/电力线路第二种工作票：1.没有待会签阶段；2.待接收阶段会有工作票号
//                if (type.equals(TicketType.MechanicalTicket.getType()) || type.equals(TicketType.PowerLineFirst.getType())
//                        || type.equals(TicketType.PowerLineSecond.getType()) || type.equals(TicketType.FirstLevelHotWork.getType())) {
//                    String code = getLastCodeByUnitAndTicketTypeNew(factory, workTicket.getUnit(), type);
//                    workTicket.setCode(code);
//                    status += 1;
//                }
//            } // 7.2 如果是会签状态，保存签名信息，生成工作票号
//            else if (status.equals(TicketStatus.COUNTERSIGN.getStatus())) {
//                workFlowService.insertByMap(factory, infoMap, status);
//                // 20211112: 电气第一种工作票/电气第二种工作票/二级动火工作票：1. 票号在会签提交阶段生成
//                if (type.equals(TicketType.ElectricalFirst.getType()) || type.equals(TicketType.ElectricalSecond.getType())
//                        || type.equals(TicketType.SecondLevelHotWork.getType())) {
//                    String code = getLastCodeByUnitAndTicketTypeNew(factory, workTicket.getUnit(), type);
//                    if (StringUtils.isEmpty(code)) {
//                        return "工作票票号生成有问题，请联系运维人员";
//                    }
//                    workTicket.setCode(code);
//                }
//            } // 7.3 如果是待接收状态：1.保存签名信息；2.将预览标志设为未预览
//            else if (status.equals(TicketStatus.ACCEPT.getStatus())) {
//                workFlowService.insertByMap(factory, infoMap, status);
//                workTicket.setPreviewFlag(1);
//                // 20211112: 电力线路第二种工作票：1. 没有待许可阶段；2. 预览标志未已预览
//                if (type.equals(TicketType.PowerLineSecond.getType())) {
//                    status += 1;
//                    workTicket.setPreviewFlag(0);
//                }
//            }
//            // 7.4 如果是待许可状态，保存签名信息，以及待许可信息
//            else if (status.equals(TicketStatus.PERMIT.getStatus())) {
//                workPermitService.insertByMap(factory, infoMap, status);
//            } // 7.5 如果是工作待终结保存签名信息，以及终结信息(工作票待终结直接调用workflowUpdateEnd接口)
//            else if (status.equals(TicketStatus.WORK_END.getStatus())) {
//                workEndService.insertByMap(factory, infoMap, status);
//                // TODO: 20211115: 一级动火/二级动火工作票，没有工作票待终结(应该不需要，直接workFlowEnd了)
//                if (type.equals(TicketType.FirstLevelHotWork.getType()) || type.equals(TicketType.SecondLevelHotWork.getType())) {
//                    status += 1;
//                }
//            }
//            // 8. 状态更新，更新主票
//            workTicket.setStatus(status + 1);
////            // 9. 将工作票的预览标志置为未预览
////            workTicket.setPreviewFlag(1);
//            lineWorkTicketService.update(factory, workTicket);
//        } else {
//            return "操作类型为：" + operation + ",请联系运维人员";
//        }
//        return null;
//    }

    /**
     * 已归档前的一个阶段会调用这个接口
     * 1. 工作票更新状态；
     * 2. 工作终结信息保存(签名数据同时保存)
     *
     * @param factory
     * @param redirectQuery
     * @throws ParseException
     */
    public void workflowUpdateEnd(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        String workTicketId = redirectQuery.getDataId();
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
        Integer status = workTicket.getStatus();
        // 20211115: 一级动火/二级动火工作票，没有工作票待终结
        String type = workTicket.getType();
        workTicket.setStatus(status + 1);
        lineWorkTicketService.update(factory, workTicket);

        String formVariables = redirectQuery.getFormVariables();
//        Map<String, String> infoMap = TextUtil.toMapFromString(formVariables);
//        workEndService.insertByMap(factory, infoMap, status);
        // 保存终结信息
        WorkEnd workEnd = JSONObject.parseObject(formVariables, WorkEnd.class);
        workEnd.setId(workEnd.getWorkEndId());

        workEndService.saveWithStatus(factory, workEnd, TicketStatus.TICKET_END.getStatus());

        // 保存签名信息
        List<WorkFlow> workFlowList = workEnd.getWorkFlowList();
        if (workFlowList != null && workFlowList.size() > 0) {
            for (WorkFlow workFLow : workFlowList) {
                workFLow.setId(workFLow.getWorkFlowId());
                workFlowService.save(factory, workFLow);
            }
        }
    }

    /**
     * 工作票作废：
     * 1. 将工作票的状态更新为已作废
     *
     * @param factory
     * @param redirectQuery
     */
    public void workflowUpdateCancel(SessionFactory factory, RedirectQuery redirectQuery) {
        String workTicketId = redirectQuery.getDataId();
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = lineWorkTicketService.getSingle(factory, workTicketQuery);
        workTicket.setStatus(TicketStatus.INVALID.getStatus());
        lineWorkTicketService.update(factory, workTicket);
    }

    public void clenWorkFlowByStatus(SessionFactory factory, String workTicketId, Integer status) {
        // 1. 清理签名数据
        WorkFlowQuery workFlowQuery = new WorkFlowQuery();
        workFlowQuery.setWorkTicketId(workTicketId);
        List<WorkFlow> workFlowList = workFlowService.getList(factory, workFlowQuery);
        // 签发状态驳回到填写状态时，签名列表为空
        if (workFlowList != null && workFlowList.size() > 0) {
            for (WorkFlow workFlow : workFlowList) {
                // 驳回到某个状态，当前状态之前的签名信息需要保存
                if (workFlow.getStatus() > status - 1) {
                    workFlowService.deleteById(factory, workFlow.getId());
                }
            }
        }
        // 2. 将工作票的预览标志置为未预览
        //this.updatePreviewFlagById(factory, workTicketId);
    }

    /**
     * 工作票号生成-新
     *
     * @param factory
     * @param unit
     * @param ticketType
     * @return
     */
    public String getLastCodeByUnitAndTicketTypeNew(SessionFactory factory, String unit, String ticketType) {
        String prefix = getPrefix(ticketType);
        if (prefix == null) {
            return null;
        }
        return StringUtils.remove(CodeTools.getCodeNo(prefix + unit, "yyMM", 3), unit);
    }

    /**
     * 工作票号生成-旧
     *
     * @param factory
     * @param unit
     * @param ticketType
     * @return
     */
    public String getLastCodeByUnitAndTicketType(SessionFactory factory, String unit, String ticketType) {
        String code;
        String prefix;
        prefix = getPrefix(ticketType);
        if (prefix == null) return null;
        // 1. 获取时间，年份的后两位+月份
        String time = new SimpleDateFormat("yyMM", Locale.CHINESE).format(new Date());
        // 2. 获取最新的流水号
        // 2.1 获取最新的工作票的票号
        String lastCode = lineWorkTicketService.getLastCodeByUnitAndType(factory, unit, ticketType);
        if (StringUtils.isNotEmpty(lastCode)) {
            Integer length = lastCode.length();
            // 2.2 获取最新的流水号
            Integer number = Integer.parseInt(lastCode.substring(length - 3, length));
            // 2.3 生成code,根据具体的数字补全前面的0：1--001；12-012；123-123
            if (number <= 8) {
                code = prefix + time + "00" + (number + 1);
            } else if (number <= 98 && number >= 9) {
                code = prefix + time + "0" + (number + 1);
            } else {
                code = prefix + time + (number + 1);
            }
        } else {
            code = prefix + time + "001";
        }

        return code;
    }

    /**
     * 工作票前缀
     *
     * @param ticketType
     * @return
     */
    private String getPrefix(String ticketType) {
        String prefix;
        if (ticketType.equals(TicketType.LineFirst.getType())) {
            prefix = "XY";
        } else if (ticketType.equals(TicketType.LineSecond.getType())) {
            prefix = "XE";
        } else {
            return null;
        }
        return prefix;
    }

    public void saveWorkFLow(SessionFactory factory, String formVariables) {
        WorkFlow workFlow = JSONObject.parseObject(formVariables, WorkFlow.class);
        String id = workFlow.getWorkFlowId();
        workFlow.setId(id);
        if (StringUtils.isNotEmpty(id)) {
            workFlowService.update(factory, workFlow);
        } else {
            workFlowService.insert(factory, workFlow);
        }
    }

}
